package clw.wumi.data.service;

import clw.wumi.data.entity.Item;
import clw.wumi.data.entity.Place;
import clw.wumi.data.repository.ItemRepository;
import clw.wumi.data.repository.PlaceRepository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author chengliwei
 * @date 2023/4/24 17:26
 */
@Service
public class ItemService {

    private final ItemRepository itemRepository;
    private final PlaceRepository placeRepository;

    public ItemService(ItemRepository itemRepository,
                       PlaceRepository placeRepository) {
        this.itemRepository = itemRepository;
        this.placeRepository = placeRepository;
    }

    public List<Item> findAllItems(String stringFilter) {
        if (stringFilter == null || stringFilter.isEmpty()) {
            return itemRepository.findAll();
        } else {
            return itemRepository.search(stringFilter);
        }
    }

    public List<Place> findAllPlaces() {
        List<Place> places = placeRepository.findAll();
        return places.stream().filter(place -> place.getParentId() != null).toList();
    }

    public void saveItem(Item item) {
        itemRepository.save(item);
    }

    public void deleteItem(Item item) {
        itemRepository.delete(item);
    }
}
